import config from './config'
import axios from 'axios'
import jsonp from 'jsonp'
import apiList from './api'
import qs from 'qs'

class SDK {
  constructor(){
    // 创建一个文件上传用的 axios 对象
    this.uploadInst = axios.create({
      baseURL:config.serverAddress,
      timeout:config.timeout,
      headers:{
        'Content-Type' : 'multipart/form-data'
      }
    })
  }
	use(name,payload){
		switch (payload.method){
			case 'jsonp':
				return this.jsonp(name,payload);
				break;
			case 'post':
				return this.post(name,payload);
				break;
      case 'upload':
        return this.upload(name,payload);
        break;
			case 'get':
			default:
				return this.get(name,payload);
				break;
		}
	};
	get(apiName,payload){return this.fetch(apiName,payload,'get')};
	post(apiName,payload){return this.fetch(apiName,payload,'post')};
	fetch(apiName,payload,requestType){
		return new Promise((resolve,reject)=> {
			const api = apiList[apiName];
			if(!api) reject({errMsg:config.errors.apiNotFound});
			const request = this.request.prepare(payload,config.serverAddress+api.url,api.require);
			// console.log('看看 request',request)
			let timeout = config.timeout;
			if(payload.timeout) timeout = payload.timeout;
			switch(requestType){
				case 'post': {
				  axios.post(request.url,
            qs.stringify(request.data),
            { headers: { 'Content-Type': api.contentType ? api.contentType : 'application/x-www-form-urlencoded' },
            timeout }).then(response => {
            resolve(response.data);
          }).catch(error => {
            reject(error);
          });
          break;
        }
				default:
					axios.get(request.url,{
						params:request.data,
						timeout:timeout
					}).then(response => {
						resolve(response.data);
					}).catch(error=>{
						reject(error);
					});
					break;
			}
		})
	};
	upload(apiName,payload){
    return new Promise((resolve,reject)=> {
      const api = apiList[apiName];
      if(!api) reject({errMsg:config.errors.apiNotFound});
      const request = this.request.prepare(payload,config.serverAddress+api.url,api.require);
      // console.log('看看 request',request)
      // 组装formData
      let fd = new FormData()
      fd.append('file',request.data.file,encodeURIComponent(request.data.file.name))
      Object.keys(request.data).forEach(key=>{
        if(key !=='file')
          fd.append(key,request.data[key])
      })
      this.uploadInst.post(api.url,fd)
        .then(response => {
        resolve(response.data);
      }).catch(error => {
        reject(error);
      });
    })
  };
	jsonp = function(apiName,payload){
		return new Promise((resolve,reject) =>{
			const api = apiList[apiName];
			if(!api) reject({errMsg:config.errors.apiNotFound});
			const request = this.request.prepare(payload,config.serverAddress+api.url,api.require);
			jsonp(request.url,null,function (err,data){
				if(err){
					console.error(err.message);
					reject(err);
				}else{
					if(data){
						resolve(data);
					}
				}
			});
		})
	};
	request = {
		prepare:function(payload,url,require){
			const request = {token:payload.token,clientid:payload.clientid,url,...payload};
			const validation = this.validate(request,require);
			if(validation) return request;
			else return false;
		},
		validate:function(request,require){
			require.map(requirement=>{
				if(request.data[requirement] === null || request.data[requirement] === undefined){
					throw config.errors.missingParam + requirement;
				}
			});
			return true;
		}
	}
}
export default new SDK();
